import re
from typing import List, Dict, Any
from datetime import datetime

from src.models.base import CourseContent, CourseChapter, CoursePoint
from src.utils.logger import get_logger

logger = get_logger(__name__)


class CourseParser:
    """课程内容解析器."""
    
    def __init__(self):
        self.chapter_keywords = [
            "章节", "章", "第一章", "第二章", "第三章", "第四章", "第五章",
            "单元", "模块", "部分", "lesson", "chapter", "unit", "module"
        ]
        self.point_keywords = [
            "要点", "重点", "核心", "关键", "主要内容", "学习目标",
            "知识点", "技能点", "point", "key", "important"
        ]
    
    def parse_course_content(self, content: str) -> CourseContent:
        """解析课程内容文本，生成结构化数据."""
        logger.info("开始解析课程内容")
        
        # 预处理文本
        processed_content = self._preprocess_content(content)
        
        # 提取课程标题
        course_title = self._extract_course_title(processed_content)
        
        # 提取章节
        chapters = self._extract_chapters(processed_content)
        
        # 如果没有明确章节，将整个内容作为一个章节
        if not chapters:
            chapters = self._create_default_chapter(processed_content)
        
        result = CourseContent(
            title=course_title,
            chapters=chapters
        )
        
        logger.info(f"课程解析完成: {course_title}, 共{len(chapters)}个章节")
        return result
    
    def _preprocess_content(self, content: str) -> str:
        """预处理文本内容."""
        # 清理多余空白字符
        content = re.sub(r'\s+', ' ', content.strip())
        
        # 统一换行符
        content = content.replace('\r\n', '\n').replace('\r', '\n')
        
        return content
    
    def _extract_course_title(self, content: str) -> str:
        """提取课程标题."""
        lines = content.split('\n')
        
        # 尝试从第一行提取标题
        if lines:
            first_line = lines[0].strip()
            if len(first_line) < 100 and any(keyword in first_line for keyword in ["课程", "教程", "培训", "学习", "course", "tutorial"]):
                return first_line
        
        # 寻找包含课程相关关键词的行作为标题
        for line in lines[:5]:  # 只检查前5行
            line = line.strip()
            if line and len(line) < 50 and any(keyword in line for keyword in ["课程", "教程", "培训"]):
                return line
        
        # 默认标题
        return "课程内容"
    
    def _extract_chapters(self, content: str) -> List[CourseChapter]:
        """提取章节信息."""
        chapters = []
        lines = content.split('\n')
        current_chapter_lines = []
        current_chapter_title = ""
        
        for line in lines:
            line = line.strip()
            if not line:
                continue
            
            # 检查是否为章节标题
            if self._is_chapter_title(line):
                # 保存当前章节
                if current_chapter_title and current_chapter_lines:
                    chapter = self._create_chapter(current_chapter_title, current_chapter_lines)
                    if chapter:
                        chapters.append(chapter)
                
                # 开始新章节
                current_chapter_title = line
                current_chapter_lines = []
            else:
                current_chapter_lines.append(line)
        
        # 保存最后一个章节
        if current_chapter_title and current_chapter_lines:
            chapter = self._create_chapter(current_chapter_title, current_chapter_lines)
            if chapter:
                chapters.append(chapter)
        
        return chapters
    
    def _is_chapter_title(self, line: str) -> bool:
        """判断是否为章节标题."""
        # 检查数字开头的标题
        if re.match(r'^\d+\.?\s*', line):
            return True
        
        # 检查包含章节关键词
        for keyword in self.chapter_keywords:
            if keyword in line:
                return True
        
        # 检查特殊格式
        if re.match(r'^第[一二三四五六七八九十\d]+[章节单元]', line):
            return True
        
        return False
    
    def _create_chapter(self, title: str, content_lines: List[str]) -> CourseChapter:
        """创建章节对象."""
        # 提取章节描述
        description = self._extract_chapter_description(content_lines)
        
        # 提取要点
        points = self._extract_points(content_lines)
        
        return CourseChapter(
            title=title,
            description=description,
            points=points
        )
    
    def _extract_chapter_description(self, content_lines: List[str]) -> str:
        """提取章节描述."""
        # 取前几行作为描述，排除明显的要点标题
        description_lines = []
        for line in content_lines[:3]:
            if not self._is_point_title(line) and len(line) > 10:
                description_lines.append(line)
        
        description = ' '.join(description_lines)
        return description[:200] if description else "本章节内容"
    
    def _extract_points(self, content_lines: List[str]) -> List[CoursePoint]:
        """提取要点."""
        points = []
        current_point = None
        current_content = []
        
        for line in content_lines:
            if self._is_point_title(line):
                # 保存当前要点
                if current_point:
                    point = self._create_point(current_point, current_content)
                    if point:
                        points.append(point)
                
                # 开始新要点
                current_point = line
                current_content = []
            else:
                current_content.append(line)
        
        # 保存最后一个要点
        if current_point:
            point = self._create_point(current_point, current_content)
            if point:
                points.append(point)
        
        # 如果没有明确要点，从内容中自动生成
        if not points:
            points = self._generate_auto_points(content_lines)
        
        return points
    
    def _is_point_title(self, line: str) -> bool:
        """判断是否为要点标题."""
        # 检查编号格式
        if re.match(r'^[\d\w]+\.?\s+', line):
            return True
        
        # 检查要点关键词
        for keyword in self.point_keywords:
            if keyword in line:
                return True
        
        # 检查特殊符号开头
        if re.match(r'^[•·▪▫○●]\s*', line):
            return True
        
        return False
    
    def _create_point(self, title: str, content_lines: List[str]) -> CoursePoint:
        """创建要点对象."""
        # 清理标题
        title = re.sub(r'^[\d\w•·▪▫○●]+\.?\s*', '', title).strip()
        
        # 生成描述
        description = self._generate_point_description(title, content_lines)
        
        # 确定级别（简单逻辑：根据内容长度判断）
        level = 1 if len(content_lines) > 2 else 2
        
        return CoursePoint(
            title=title,
            description=description,
            level=level
        )
    
    def _generate_point_description(self, title: str, content_lines: List[str]) -> str:
        """生成要点描述."""
        if content_lines:
            # 取第一行作为描述
            description = content_lines[0].strip()
            return description[:100] if description else f"{title}的相关内容"
        
        return f"关于{title}的要点内容"
    
    def _generate_auto_points(self, content_lines: List[str]) -> List[CoursePoint]:
        """自动生成要点（当无法识别明确要点时）."""
        points = []
        
        # 将内容按段落分割
        paragraphs = []
        current_paragraph = []
        
        for line in content_lines:
            if line.strip():
                current_paragraph.append(line)
            else:
                if current_paragraph:
                    paragraphs.append(' '.join(current_paragraph))
                    current_paragraph = []
        
        if current_paragraph:
            paragraphs.append(' '.join(current_paragraph))
        
        # 每个段落生成一个要点
        for i, paragraph in enumerate(paragraphs[:5], 1):  # 最多5个要点
            if len(paragraph) > 20:
                title = f"要点{i}"
                description = paragraph[:100] + "..." if len(paragraph) > 100 else paragraph
                
                points.append(CoursePoint(
                    title=title,
                    description=description,
                    level=1
                ))
        
        return points
    
    def _create_default_chapter(self, content: str) -> List[CourseChapter]:
        """创建默认章节（当无法识别章节时）."""
        lines = [line.strip() for line in content.split('\n') if line.strip()]
        
        # 生成要点
        points = self._extract_points(lines)
        
        chapter = CourseChapter(
            title="主要内容",
            description="课程核心内容概述",
            points=points
        )
        
        return [chapter]